<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<script>
    var socket;
    var port;
    //判断当前浏览器是否支持websocket
    if(window.WebSocket) {
        // 监听服务端发送的消息，和服务端 uri 相同 长连接
        socket = new WebSocket("ws://localhost:8802/index");
        // 相当于channelRead0, ev 收到服务器端回送的消息
        // onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;
        socket.onmessage = function (ev) {
            console.log(ev.data)
            if (ev.data.split(":")[0]==="port"){
                port =  ev.data.split(":")[1];
                console.log(port)
            }else {
                const rt = document.getElementById("responseText");
                rt.value = rt.value + "\n" + ev.data;
            }
        }

        //相当于连接开启(感知到连接开启)
        socket.onopen = function (ev) {
            console.log(ev)
            const rt = document.getElementById("responseText");
            rt.value = "connected server..."
        }

        //相当于连接关闭(感知到连接关闭)
        socket.onclose = function (ev) {
            const rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "connection closed..."
        }
    } else {
        alert("当前浏览器不支持websocket")
    }

    //发送消息到服务器
    function send(message) {
        if (!window.socket) { //先判断socket是否创建好
            return;
        }
        if (socket.readyState === WebSocket.OPEN) {
            //通过socket 发送消息
            socket.send(message)  // 发送到服务器，服务器返回信息
            document.getElementById('message').value=''
        } else {
            alert("连接没有开启");
        }
    }
</script>

<div>
    <h4>聊天信息</h4>
    <p>👤：自己 📱：对方</p>
    <label for="responseText"></label>
    <textarea id="responseText" style="height: 400px;width: 80%;position: center"></textarea>
    <input type="button" value="清空记录" onclick="document.getElementById('responseText').value=''">
</div>

<div style="margin-top: 30px">
    <form onsubmit="return false">
        <label>
            <textarea id="message" name="message" style="height: 100px;width: 80%"></textarea>
        </label>
        <input type="button" value="发送" onclick="send(this.form.message.value)">
    </form>
</div>


</body>
</html>